package dtls;

import java.io.InputStream;
import java.net.InetSocketAddress;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;

import org.eclipse.californium.elements.RawData;
import org.eclipse.californium.elements.RawDataChannel;
import org.eclipse.californium.scandium.DTLSConnector;
import org.eclipse.californium.scandium.config.DtlsConnectorConfig;

public class DtlsServer {
	
	public static final int DEFAULT_PORT = 5684;
	public static final String TRUST_STORE_PASSWORD = "222222";
	public static final String TRUST_STORE_LOCATION = "trustStore.jks";
	public static final String KEY_STORE_PASSWORD = "111111";
	public static final String KEY_STORE_LOCATION = "keyStore.jks";

	public static void main(String[] args) throws Exception {
		
		InputStream in = DtlsServer.class.getResourceAsStream(KEY_STORE_LOCATION);
		KeyStore keyStore = KeyStore.getInstance("jks");
		keyStore.load(in, KEY_STORE_PASSWORD.toCharArray());
		in.close();
		
		KeyStore trustStore = KeyStore.getInstance("jks");
		in = DtlsServer.class.getResourceAsStream(TRUST_STORE_LOCATION);
		trustStore.load(in, TRUST_STORE_PASSWORD.toCharArray());
		in.close();
		
		Certificate[] cert = new Certificate[1];
		cert[0] = trustStore.getCertificate("root");
		
		DtlsConnectorConfig.Builder builder = 
				new DtlsConnectorConfig.Builder(new InetSocketAddress(DEFAULT_PORT));
		builder.setIdentity((PrivateKey)keyStore.getKey("certificatekey", KEY_STORE_PASSWORD.toCharArray()), 
				keyStore.getCertificateChain("certificatekey"), true);
		builder.setTrustStore(cert);
		final DTLSConnector connector = new DTLSConnector(builder.build());
		connector.setRawDataReceiver(new RawDataChannel() {
			
			@Override
			public void receiveData(RawData raw) {
				System.out.println("server receive data:" + new String(raw.getBytes()));
				connector.send(new RawData("server response".getBytes(), raw.getAddress(), raw.getPort()));
			}
		});
		connector.start();
	}
}
